package com.sunny.structure.lineartable.singlelinked;

/**
 * 归并排序链表
 *
 * @author Sunny
 * @date 2020/5/19
 */
public class Interview2 {

    public static ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode mid = getMid(head);
        ListNode right = mid.next;
        mid.next = null; //咬断链表
        ListNode node = merge(sortList(head), sortList(right));
        return node;
    }

    public static ListNode getMid(ListNode head){
        if (head == null) {
            return null;
        }

        ListNode fast = head;
        ListNode slow = head;

        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    public static ListNode merge(ListNode left, ListNode right) {
        ListNode pre = new ListNode(0);
        ListNode cur = pre;

        // 比较左右链表
        while (left != null && right != null) {
            if (left.value <= right.value) {
                cur.next = left;
                cur = cur.next;
                left = left.next;
            } else {
                cur.next = right;
                cur = cur.next;
                right = right.next;
            }
        }
        if (left != null) {
            cur.next = left;
        }
        if (right != null) {
            cur.next = right;
        }

        return pre.next;
    }

    public static ListNode init() {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(8);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(6);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(4);
        ListNode node7 = new ListNode(7);
        ListNode node8 = new ListNode(2);
        ListNode node9 = new ListNode(9);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;
        node7.next = node8;
        node8.next = node9;
        return node1;
    }

    public static void main(String[] args) {
        ListNode node = init();

        ListNode head = sortList(node);
        while (head != null) {
            System.out.print(head.value + " ");
            head = head.next;
        }
    }
}
